package com.base.myproject.client.HR.Training;
/*部门入职培训检查*/
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.base.myproject.client.HR.bcode.BcodeSelectDialog;
import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BaseTreeStore;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.BO.TreeNodeModelData;
import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.tools.Tools;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.TreePanelEvent;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.StoreFilterField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.CheckColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckCascade;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel.CheckNodes;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Label;

public class Training_DepOrientationCheck extends BaseJDBCPanel{
	
	String treeDepId = null;                       //将当前树形结构中选中的部门id保存
	String treeDepName = null;                     //将当前树形结构中选中的部门name保存
	
	TreePanel<TreeNodeModelData> treepanel = null;
	
	StoreFilterField field = null;     
	
	Button add = new Button("添加");
	BcodeSelectDialog<TreeNodeModelData> bsd_add ;
	
	BaseComboBoxForm<BaseModelData> bcode = new BaseComboBoxForm<BaseModelData>("bcode","bname","bcode","",true);
	BaseComboBoxForm<BaseModelData> departmentCode = new BaseComboBoxForm<BaseModelData>("id","name","SystemInfo","where name is not null and id is not null",true);
	BaseComboBoxForm<BaseModelData> sectionCode = new BaseComboBoxForm<BaseModelData>("id","name","SystemInfo","where name is not null and id is not null and len(id)=(select max(len(id)) from systeminfo)",true);
	String results = null;
	String bcode2 = Env.getEnvbcode();
	
	public Training_DepOrientationCheck(){
		String sql = "select substring('id like '''+replace(permissionsbcode,';','%'' or id like '''),9," +
		"len('id like '''+replace(permissionsbcode,';','%'' or id like '''))-21) as result from" +
		" busipermissions where bcode = '"+bcode2+"' and busicode = 8010";
		final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService2.getDataSet(sql, new AsyncCallback<DataSet>(){
		@Override
			public void onFailure(Throwable caught) {	
			}
			@Override
			public void onSuccess(DataSet result) {  
			   results = result.getValue(0, "result");
			   init();
			}
		});
	}
	
	public void complete(){
		super.complete();
	}
	
	public void init(){
		initTreePanel();
    	initWeigetx();	
    	registerMainStore(store);
		registerStore(store);
	}
	
	private void initWeigetx(){
		HorizontalPanel cp=new HorizontalPanel();
		VerticalPanel vp=new VerticalPanel();		
		HorizontalPanel s=new HorizontalPanel();
		s.setHeight("25");
		vp.add(this.createQuery());
		vp.add(this.createAdd());
		vp.add(this.getBaseGrid());
	//	vp.add(this.getBaseFormPanel());
		cp.add(treepanel);
		cp.add(vp);
		cp.setStyleName("hp_css");//添加一个css属性
		add(cp);
		this.layout();
		add.addListener(Events.Select, getListener());
		sectionCode.addListener(Events.Changed, getListener());
	}
	
	BaseTreeStore<TreeNodeModelData> treeStore = null;
	private TreePanel<TreeNodeModelData> getTreePanel(){
		if(treepanel == null){
			initTreePanel();
		}
		return treepanel;
	}
	
	private BaseTreeStore<TreeNodeModelData> getTreeStore(){
		if (treeStore == null) {
			initTreeStore();
		}
		return treeStore;
	}
	
	private BaseTreeStore<TreeNodeModelData> initTreeStore(){
		StoreInfo info = new StoreInfo();
		String sql2 = "select icode,id,name from SystemInfo where id like "+results+" order by id asc";
		info.setSql(sql2);
		info.setTreesortcolumn("id");
		info.setKeyname(new String[]{ "icode" });
		info.setTablename("SystemInfo");
		treeStore = new BaseTreeStore<TreeNodeModelData>(info,false);
		treeStore.load();
		return treeStore;
	}
	
	private void initTreePanel(){
		treepanel = new TreePanel<TreeNodeModelData>(getTreeStore());
		treepanel.setSize(150, 450);
		treepanel.setBorders(true);
		treepanel.setDisplayProperty("name");
		treepanel.setCheckStyle(CheckCascade.PARENTS);
		treepanel.setCheckNodes(CheckNodes.BOTH);
		treepanel.setCheckable(false);
		treepanel.setAutoLoad(true);
		treepanel.setCaching(true);
		
		treepanel.addListener(Events.OnClick,
			new Listener<TreePanelEvent<TreeNodeModelData>>() {
				public void handleEvent(TreePanelEvent<TreeNodeModelData> be) {
					String id = be.getItem().get("id").toString();
					treeDepId=id;
					treeDepName=be.getItem().get("name").toString();
					set_grid(id);
				}
			});
	}
	public void set_grid(String id){
		StoreInfo info2 = new StoreInfo();
		info2.setTablename("hr_DepartmentalOrientationChecklist");
		info2.setKeyname(new String[] { "icode" });
		String where=" where 1=1 and ";
		if(id.length()<5){
			where=where+" sectionCode like '" +id+ "%25'";
		}else{
			where=where+" sectionCode = '" +id+ "'";
		}
		info2.setSql("select * from hr_DepartmentalOrientationChecklist "+where);//这里sql的linke %%  有问题
		grid.getStore().setStoreinfo(info2);
		grid.getStore().reload();
		grid.getView().refresh(true);
      }
	
	private FieldSet createQuery(){
		FieldSet query = new FieldSet();
		query.setHeading("查询操作");
		
		HorizontalPanel s=new HorizontalPanel();
		s.setHeight("25");
		
		s.add(new Label("快速查询: "));
		cread_field();
		s.add(field);
		query.add(s);
		return query;
	}
	
	private FieldSet createAdd(){
		
		bsd_add = new BcodeSelectDialog<TreeNodeModelData>(){
			public void doposted(List<TreeNodeModelData> modeldatalist) {
				if(modeldatalist.size()>0)
				{
					String bcode_str="";
					for(int i=0;i<modeldatalist.size();i++){
						bcode_str=bcode_str+";"+modeldatalist.get(i).get("bname");
					}
					bcode_str=bcode_str.substring(1, bcode_str.length());
					this.setEmptyText(bcode_str);
				}
			}
		};
		bsd_add.setNeesreselect(false);
		bsd_add.setEmptyText("未选择数据");
		
		FieldSet addHandle = new FieldSet();
		addHandle.setHeading("添加操作");
		
		HorizontalPanel s=new HorizontalPanel();
		s.setHeight("25");
		
		s.add(new Label("选择人员:"));
		s.add(bsd_add);
		add.setWidth(60);
		s.add(add);
		addHandle.add(s);
		return addHandle;
	}
	
	public void setCheckNodes(CheckNodes checkNodes) {
		treepanel.setCheckNodes(checkNodes);
	}
	
	BaseStore<BusiObject> store = null;
	BaseStore<BusiObject> getStore(){
	if(store==null) 
	{
		createStore();
	}
	return store;
	}
	
	ModelType type = new ModelType();
	public BaseStore<BusiObject> createStore(){
		
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		
		type.addField("bcode");
		type.getField("bcode").setType(String.class);
		
		type.addField("micode");
		type.getField("micode").setType(Long.class);
		
		type.addField("departmentCode");
		type.getField("departmentCode").setType(String.class);
		
		type.addField("sectionCode");
		type.getField("sectionCode").setType(String.class);
		
		type.addField("joinDate");
		type.getField("joinDate").setType(Date.class);
		
		type.addField("commitDate");
		type.getField("commitDate").setType(Date.class);
		
		type.addField("office");
		type.getField("office").setType(String.class);
		
		type.addField("sectionTrainingChampion");
		type.getField("sectionTrainingChampion").setType(String.class);
		
		type.addField("attendanced");
		type.getField("attendanced").setType(Boolean.class);
		
		type.addField("grade");
		type.getField("grade").setType(String.class);
		
		StoreInfo info = new StoreInfo();
		info.setTablename("hr_DepartmentalOrientationChecklist");
		info.setKeyname(new String[] { "icode"});
		info.setSql("select * from hr_DepartmentalOrientationChecklist");
		store = new BaseStore<BusiObject>(type, info);
		return store;
	}
	
	
	BaseGrid grid = null;
	public BaseGrid getBaseGrid() {
		if (grid == null) {
			createGrid();
		}
		return grid;
	}
	
	private void createGrid(){
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());
		DateField dateField1 = new DateField();
		
		ColumnConfig C4 = new ColumnConfig("departmentCode", "部门名称", 80);
		C4.setRenderer(departmentCode);
		departmentCode.setReadOnly(true);
		departmentCode.setFireChangeEventOnSetValue(true);
		departmentCode.setName("departmentCode");
		C4.setEditor(departmentCode.getCelEditor());
		columns.add(C4);
		
		ColumnConfig C5 = new ColumnConfig("sectionCode", "分部门名称", 80);
		sectionCode.setReadOnly(true);
		sectionCode.setName("sectionCode");
		C5.setRenderer(sectionCode);
		C5.setEditor(sectionCode.getCelEditor());
		columns.add(C5);
		
		ColumnConfig C3 = new ColumnConfig("bcode", "员工姓名", 80);
		columns.add(C3);
		
//		GridCellRenderer<ModelData>	renderer = new GridCellRenderer<ModelData>() {              
//		      public String render(ModelData model, String property, ColumnData d, int rowIndex,
//		          int colIndex, ListStore<ModelData> store, Grid<ModelData> grid) {             
//		    	  if(model.get(property) !=null && model.get(property) instanceof ModelData)
//		    	  {
//		    		  return ((ModelData)model.get(property)).get("value");
//		    	  }                                                                            
//		    	  return model.get(property);                                                     
//		      }                                                                                 
//		    };  
		C3.setRenderer(bcode);

		
		ColumnConfig C7 = new ColumnConfig("joinDate", "入职日期", 80);
	    C7.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C7);
		
		ColumnConfig C8 = new ColumnConfig("commitDate", "提交日期", 80);
		DateField commitdate = new DateField();
		commitdate.setName("commitDate");
		C8.setEditor(new CellEditor(commitdate));
	    C8.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C8);
		
		ColumnConfig C11 = new ColumnConfig("office", "职位", 80);
		TextField<String> office = new TextField<String>();
		office.setName("office");
		C11.setEditor(new CellEditor(office));
		columns.add(C11);
		
		ColumnConfig C12 = new ColumnConfig("sectionTrainingChampion", "分部培训负责人", 100);
		TextField<String> sectionTrainingChampion = new TextField<String>();
		sectionTrainingChampion.setName("sectionTrainingChampion");
		C12.setEditor(new CellEditor(sectionTrainingChampion));
		columns.add(C12);

		ColumnModel cm = new ColumnModel(columns);
		grid = new BaseGrid(getStore(), cm){
			@SuppressWarnings("unchecked")
			public void addnewrecord() {
				if (treeDepId == null ) {
					MessageBox.alert("警告", "请选择一个部门后再添加新信息", null);
					return;
				}
				HashMap hp = new HashMap();
				hp.put("sectionCode", treeDepId);
				grid.getStore().add(hp);
			}
		};
		
		CheckColumnConfig checkColumn = new CheckColumnConfig("attendanced", "是否参加", 80);  
		CellEditor checkBoxEditor = new CellEditor(new CheckBox());  
		checkColumn.setEditor(checkBoxEditor);  
		columns.add(checkColumn);
		
		ColumnConfig C9 = new ColumnConfig("grade", "评定(1/0.5)", 80);
		TextField<String> grade = new TextField<String>();
		grade.setName("grade");
		C9.setEditor(new CellEditor(grade));
		columns.add(C9);
		
		cbs.setSelectionMode(SelectionMode.SINGLE);
		grid.setSelectionModel(cbs);
		Tools.setResize(grid,0.86,0.65);
	}
	
	int sync = 0;                                                      
	Listener<BaseEvent> defaultlistener;                               
                                                                     
	public Listener<BaseEvent> getListener() {                                
		if(defaultlistener!=null)                                        
		{                                                                
			return defaultlistener;                                        
		}                                                                
                                                                     
		defaultlistener = new Listener<BaseEvent>() {                    
			public void handleEvent(BaseEvent be) {                        
				sync++;                                                    
				try {                                                      
					if (sync == 1) {                                   
						if (be.getType() == Events.Select) { 
							if(be.getSource().equals(add)){
								List<TreeNodeModelData>  selectchecklist=bsd_add.getTree().getCheckedSelection();
								String bcode_str = "";
								for(final TreeNodeModelData tnmd:selectchecklist){
									bcode_str += "'"+tnmd.get("bcode") + "',";
								}
								String bcodes = bcode_str.substring(0, bcode_str.length()-1);
								final String sql = "select bcode.bcode,bname,systemid,up_department,entrydate,employoutertitle from bcode,bcode_job where bcode.bcode=bcode_job.bcode and bcode.bcode in ("+bcodes+")";
								final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT.create(com.base.myproject.client.tools.GreetingService.class);
								   greetingService.getDataSet(sql, new AsyncCallback<DataSet>(){
									@Override
									public void onFailure(Throwable caught) {	
										MessageBox.alert("Error"," 服务器繁忙......", null);
									}
									@Override
									public void onSuccess(DataSet result) {	
										for(int i = 0;i < result.getRowCount();i++){
											BusiObject bo = new BusiObject();
											bo.set("bcode", result.getValue(i, "bcode"));
											bo.set("departmentCode", result.getValue(i, "up_department"));
											bo.set("joinDate",dateFormat(result.getValue(i, "entrydate")));
											bo.set("sectionCode",result.getValue(i, "systemid"));
											bo.set("office", result.getValue(i, "employoutertitle"));
											getStore().add(bo);
										}
										
									}
								});
							}
						}else if(be.getType() == Events.OnBlur){
							
						}else if(be.getType() == Events.OnClick){
							
						} else if (be.getType() == Events.Changed){
						
						}else if (be.getType() == Events.KeyUp) { 
							if (be instanceof ComponentEvent) {                    
								if (((ComponentEvent)be).getKeyCode() == 13){       // 回车                    
								}                          
							}                                  
						}                                          
					}                                                  
				} finally {                                                
					sync--;                                            
				}                                                          
			}                                                              
		};                                                               
		return defaultlistener;                                          
	}          
	
	protected boolean Select(Store<BusiObject> store,
			BusiObject parent, BusiObject record, String property,
			String filter) {
		for (int i = 0; i < type.getFieldCount(); i++) {

			Object name = record.get(type.getField(i).getName());
			
			//TODO
			if (name!=null&&name.toString().indexOf(filter.toLowerCase()) != -1) {
				return true;
			}
		}
	
		return false;
	}	
	
	public void cread_field(){
		field = new StoreFilterField<BusiObject>() {
			@Override
			protected boolean doSelect(Store<BusiObject> store,
					BusiObject parent, BusiObject record, String property,
					String filter) {

			return	Select(store,parent,record,property,filter);
			}
			@Override
			protected void onFilter() {
				super.onFilter();

				// grid.getSelectionModel().select(0);
			}
		};
		field.setAutoWidth(true);
		field.setToolTip("对当前部门数据进行查找");
		field.bind(getStore());
		this.field = field;
	}
	
	public Date dateFormat(String date){
		Date df_date = new Date();
		String[] strdates = date.split("-");
		int year = Integer.parseInt(strdates[0]);
		int month = Integer.parseInt(strdates[1]);
		int day = Integer.parseInt(strdates[2].substring(0,2));
		df_date.setYear(year-1900);
		df_date.setMonth(month-1);
		df_date.setDate(day);
		return df_date;
	}
}
